
package org.jetnuke.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.PollData;

public class GenericPollDataDAO  implements
		org.jetnuke.dao.PollDataDAO {

	private List processSelectAll(ResultSet rs) throws Exception {
		List list = new ArrayList();
		while (rs.next()) {
			PollData u = new PollData();
			fillPollDataFromResultSet(u,rs);			
			list.add(u);
		}
		
		return list;
	}

	/**
	 * @param u
	 * @param rs
	 */
	private void fillPollDataFromResultSet(PollData u, ResultSet rs) throws Exception{
		u.setOPTIONCOUNT(rs.getInt("OPTIONCOUNT"));
		u.setOPTIONTEXT(rs.getString("OPTIONTEXT"));
		u.setPOLLID(rs.getInt("POLLID"));
		u.setVOTEID(rs.getInt("VOTEID"));
		
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.PollDataModel#selectByPollIDOrderVoteID(int)
	 */
	public List selectByPollIDOrderVoteID(int pollID) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("PollDataModel.selectByPollIDOrderVoteID"));
		p.setInt(1,pollID);
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();
		
		return list;
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.PollDataModel#retrieveByPK(int, int)
	 */
	public PollData retrieveByPK(int pollID, int voteID)throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("PollDataModel.selectByID"));
		p.setInt(1, pollID);
		p.setInt(2,voteID);
		
		ResultSet rs = p.executeQuery();
		PollData  s = new PollData();
		
		if (rs.next()) {
			fillPollDataFromResultSet(s, rs);
		}
		
		rs.close();
		p.close();

		return s;
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.PollDataModel#update(org.jetnuke.entities.PollData)
	 */
	public void update(PollData dt)throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("PollDataModel.update"));
		p.setInt(1,dt.getOPTIONCOUNT());
		p.setString(2,dt.getOPTIONTEXT());
		p.setInt(3,dt.getPOLLID());
		p.setInt(4,dt.getVOTEID());
		p.executeUpdate();
		p.close();
		
	}

}
